<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>入库管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 前置信息 -->
    <h5>退货入库列表</h5>
    <el-form :inline="true" :model="formInline" class="user-search" >
      <el-form-item label="入库单号">
        <el-input size="small" clearable v-model="formInline.warehouseCode" placeholder="入库单号"></el-input>
      </el-form-item>
      <el-form-item label="关联采购订单">
        <el-input size="small" clearable v-model="formInline.warehouseName" placeholder="关联采购订单"></el-input>
      </el-form-item>
      <el-form-item label="入库单状态">
        <el-input size="small" clearable v-model="formInline.warehouseName" placeholder="入库单状态"></el-input>
      </el-form-item>
      <el-form-item>
        <span style="margin-right: 142px"></span>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
      <br>
      <el-form-item label="收货仓库">
        <el-input size="small" clearable v-model="formInline.warehouseName" placeholder="入库单状态"></el-input>
      </el-form-item>
      <el-form-item label="物流单号">
        <span style="margin-left: 27px">
          <el-input size="small" clearable v-model="formInline.warehouseName" placeholder="入库单状态"></el-input>
        </span>
      </el-form-item>
      <el-form-item label="入库时间" label-width="80px">
        <template>
          <el-date-picker
            class="custom-time-picker"
            size="small"
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="">重置</el-button>
      </el-form-item>
      <br>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="warning" @click="handleBatchDel">批量删除</el-button>
<!--        <el-dropdown size="small">-->
<!--          <el-button size="small">-->
<!--            更多菜单<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--          </el-button>-->
<!--          <el-dropdown-menu slot="dropdown">-->
<!--            <el-dropdown-item>批量删除入库</el-dropdown-item>-->
<!--            <el-dropdown-item>批量</el-dropdown-item>-->
<!--          </el-dropdown-menu>-->
<!--        </el-dropdown>-->
      </el-form-item>
    </el-form>
<!--    <el-form :inline="true" :model="formInline" class="returnIn-search">-->
<!--    </el-form>-->

    <!--列表-->
    <el-table size="small" @selection-change="handleSelectionChange" :data="listData" highlight-current-row
              v-loading="loading" border element-loading-text="拼命加载中" style="cwidth: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column
        prop="inboundNo"
        label="入库单号"
        width="180"
        sortable>
      </el-table-column>
      <el-table-column
        prop="returnOrderNo"
        label="退货订单号"
        width="180"
        sortable>
      </el-table-column>
      <el-table-column
        prop="logisticsCompany"
        label="物流公司"
        sortable>
      </el-table-column>
      <el-table-column
        prop="warehouseCode"
        label="退货仓库"
        sortable>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        sortable>
      </el-table-column>
      <el-table-column
        prop="inboundTime"
        label="入库时间"
        sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="showDetails(scope.row)">查看</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(scope.$index, scope.row)">确认拣货</el-button>
          <el-button
            size="mini"
            type="text"
            @click="deletereturnIn(scope.row.id)">关闭</el-button>
        </template>
      </el-table-column>
    </el-table>


<!--    查看dialog-->
    <el-dialog
      title="退货入库详情"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose">
      <div style="display: flex; flex-wrap: nowrap;">
        <p v-if="currentRow.inboundNo" style="margin-right: 10px;">入库单号: {{ currentRow.inboundNo }}</p>
        <p v-if="currentRow.returnOrderNo" style="margin-right: 10px;">退货订单号: {{ currentRow.returnOrderNo }}</p>
        <p v-if="currentRow.warehouseCode">退货仓库: {{ currentRow.warehouseCode }}</p>
      </div>
      <div style="display: flex; flex-wrap: nowrap;">
        <p v-if="currentRow.status" style="margin-right: 10px;">状态: {{ currentRow.status }}</p>
        <p v-if="currentRow.createTime">创建时间: {{ currentRow.createTime }}</p>
      </div>
      <h5>物流信息</h5>
      <div style="display: flex; flex-wrap: nowrap;">
        <p style="margin-right: 10px;">物流公司: {{ currentRow.logisticsCompany }}</p>
        <p >物流单号: {{ currentRow.logisticsNo }}</p>
      </div>
      <!--列表-->
      <el-table size="small" @selection-change="handleSelectionChange" :data="listData" highlight-current-row
                v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
        <el-table-column align="center" type="selection" width="60">
        </el-table-column>
        <el-table-column
          prop="inboundNo"
          label="入库单号"
          width="180"
          sortable>
        </el-table-column>
        <el-table-column
          prop="returnOrderNo"
          label="退货订单号"
          width="180"
          sortable>
        </el-table-column>
        <el-table-column
          prop="logisticsCompany"
          label="物流公司"
          sortable>
        </el-table-column>
        <el-table-column
          prop="warehouseCode"
          label="退货仓库"
          sortable>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          sortable>
        </el-table-column>
        <el-table-column
          prop="inboundTime"
          label="入库时间"
          sortable>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="showDetails(scope.row)">确认入库</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.$index, scope.row)">确认拣货</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>


  </span>
    </el-dialog>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" v-model="pageparm" @callFather="callFather"></Pagination>

    <!-- 添加/编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="入库姓名" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入入库姓名"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input size="small" v-model="editForm.age" auto-complete="off" placeholder="请输入入库年龄"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input size="small" v-model="editForm.sex" auto-complete="off" placeholder="请输入性别"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>

    <!--   文件上传-->
    <el-dialog title="Excel导入功能" :visible.sync="importvis" width="30%">
      <el-upload
        class="upload-demo"
        action="/api/returnIn/importreturnIn"
        :on-success="upload">
        <el-button size="small" type="primary">点击导入Excel文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且不超过50MB
          <a href="http://localhost:8080/tem.xlsx">点击下载Excel模板</a> </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import {returnInList, returnInStatus, returnInSave, returnInEdit, returnInDelete, returnInBatchDel} from '../../api/ReturnInMG'
import axios from "axios";
import {get} from "echarts/lib/component/toolbox/featureManager";

export default {
  name: "returnIn",
  data() {
    // 校验手机号
    var validatePhone = (rule, value, callback) => {
      const reg = /^1[356789]\d{9}$/;
      if (value === '') {
        callback(new Error('手机号不能为空'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    return {
      dialogVisible:false,//dialog是否可见
      importvis:false,
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',
      editForm: {
        name: '',
        age: 0,
        sex: '',
        birthday: '',
      },
      // rules表单验证
      rules: {
        name: [
          {required: true, message: '请输入入库姓名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ]
      },
      formInline: {
        pageNum: 1,
        pageSize: 10,
        name: '',
      },
      // 删除
      seletedata: {
        ids: '',
      },
      returnInparm: [], //搜索权限
      listData: [], //入库数据
      currentRow: {
        logisticsNo:'',
        logisticsCompany:'',
      }, // 初始化为空对象，而不是null
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      returnInStatus: true,
      multipleSelection: []
    }
  },

  // 注册组件
  components: {
    Pagination
  },

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
  },

  // async created() {
  //   try {
  //     const data = await this.getdata(this.formInline);
  //     this.fetchLogisticsInfo(data);
  //   } catch (error) {
  //     console.error('Error fetching data:', error);
  //   }
  // },
  watch: {
    // 监听currentRow的变化
    // currentRow: {
    //   handler(newVal, oldVal) {
    //     if (newVal && newVal !== oldVal) {
    //       this.fetchLogisticsInfo();
    //     }
    //   },
      // 使用深度监听，因为我们只关心属性的变化
      // deep: true,
      // 立即执行handler，设置为true可以在初始化时触发一次
      // immediate: false // 根据需要设置，如果需要在组件创建时立即触发则设置为true
    // }
  },
  methods: {
    //获取当前行数据详细信息
    showDetails(row) {
      this.currentRow = { ...row }; // 初始设置currentRow为表格中的行数据的一个副本
      this.dialogVisible = true; // 显示对话框
      // 发送axios请求获取当前行的详细信息
      axios.get(`/api/inbound/${this.currentRow.id}`)
        .then(response => {
          // 假设response.data包含了详细数据
          this.currentRow = { ...this.currentRow, ...response.data }; // 合并详细信息到currentRow
          // 查询入库单号对应物流公司
          this.fetchLogisticsInfo(); // 调用新函数来获取物流信息
        })
        .catch(error => {
          console.error('Error fetching details:', error);
          // 可能需要处理错误情况，比如关闭对话框或显示错误信息
          this.dialogVisible = false; // 如果出错，关闭对话框
        });
    },
    fetchLogisticsInfo(data) {
      // if (!this.currentRow.inboundNo) {
      //   // 如果inboundNo为空，则不执行请求
      //   return;
      // }
      axios.get(`/api/logisticsinfo/byInboundNo/${this.currentRow.inboundNo}`)
        .then(response => {
          // 假设response.data是物流信息的对象
          const logisticsInfo = response.data; // 直接使用response.data，如果后端没有额外包装
          console.log(logisticsInfo);
          // 合并物流信息到currentRow，只选择需要的属性
          this.currentRow = {
            ...this.currentRow,
            logisticsCompany: logisticsInfo.logisticsCompany, // 这是物流公司
            logisticsNo: logisticsInfo.logisticsNo, // 这是物流单号
          };
          console.log(logisticsInfo);
        })
        .catch(error => {
          // 处理错误
          console.error('Error fetching logistics info:', error);
          this.showError('获取物流信息时出错'); // 确保这个方法已定义
          // 您可以考虑不关闭对话框，而是显示错误消息
        });
    },

    // 处理dialog关闭
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },

    upload(res){
      if(res.code == '20000'){
        //成功
        this.importvis=false;
        this.getdata(this.formInline)
      }else {
        this.$message({
          type: 'warning',
          message: '嗨，导入失败！！！！'
        })
      }
    },

    exportExcel(){
      // 导出Excel
      axios.request({
        url: 'api/returnIn/returnInExport',
        method: 'get',
        responseType: 'blob',  // 请求文件
      }).then(ret => {
        this.download(ret,"入库表")
      })
    },
    // 下载excel的工具方法
    download(res, name) {
      if (!res) {
        return;
      }
      console.log("res", res)
      let url = window.URL.createObjectURL(new Blob([res.data],
        {type: "application/vnd.ms-excel"}));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', name);
      document.body.appendChild(link);
      link.click();
    },

    getdata(formInline) {
      console.log(formInline)
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      returnInList(formInline)
        .then(res => {
          this.loading = false
          if (res.code != 20000) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            const pageInfo = res.data;
            this.listData = pageInfo.list;
            // 分页赋值
            this.pageparm.currentPage = this.formInline.pageNum
            this.pageparm.pageSize = this.formInline.pageSize
            this.pageparm.total = pageInfo.total
            console.log(this.pageparm)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('入库信息加载失败，请稍后再试！')
        })
    },

    callFather(pageparam) {
      this.formInline.pageNum = pageparam.pageNum;
      this.formInline.pageSize = pageparam.pageSize;
      this.getdata(this.formInline)
    },

    search() {
      // console.log(this.formInline)
      this.getdata(this.formInline)
    },

    handleAdd() {
      this.editFormVisible = true;
      this.title = "添加";
      // 表单置空
      this.editForm = {}
    },

    closeDialog() {
      this.editFormVisible = false;
      this.getdata(this.formInline)
    },

    submitForm(editForm) {
      // 点击提交按钮会校验输入框
      this.$refs[editForm].validate((valid) => {
        // 如果校验通过再发请求
        if (valid) {
          if (this.title == "添加") {
            // 实现添加
            returnInSave(this.editForm).then(res => {
              if (res.code = 20000) {
                this.editFormVisible = false;
                this.$message.success({
                  message: '入库添加成功',
                  duration: 500
                })
                this.getdata(this.formInline)
              } else {
                this.$message.error({
                  message: '入库添加失败',
                  duration: 500
                })
              }
            })
          } else if (this.title = "编辑") {
            console.log(this.editForm)
            returnInEdit(this.editForm).then(res => {
              if (res.code = 20000) {
                this.editFormVisible = false;
                this.$message.success({
                  message: '入库更新成功',
                  duration: 500
                })
                this.getdata(this.formInline)
              } else {
                this.$message.error({
                  message: '入库更新失败',
                  duration: 500
                })
              }
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    handleEdit(index, rowData) {
      console.log(index,rowData)
      this.title = "编辑"
      this.editForm = rowData;
      this.editFormVisible = true;
    },

    deletereturnIn(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        returnInDelete(id).then(res => {
          if (res.code == 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getdata(this.formInline)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    handleSelectionChange(val) {
      // val是数组,其中是前端框架自己封装的,其实是勾选的每一行数据对象
      // console.log(val)
      var idArr = [];
      for (var i = 0; i < val.length; i++) {
        var obj = val[i];
        //console.log(obj)
        idArr.push(obj.id);
      }
      // console.log(idArr)
      this.multipleSelection = idArr;
    },

    handleBatchDel() {
      this.$confirm('批量删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        returnInBatchDel({
          list:this.multipleSelection
        }).then(res => {
          if (res.code == 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.formInline.pageNum = 1;
            this.getdata(this.formInline)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>

</style>
